﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.CallRoute;

public partial class User_Customer_Maintain : PageBase
{

    private const string REQUEST_LIST_ID = "MobileUserID";
    private const string ROUTE_ID = "id";
    private const string RESPONSE_LIST_MAINTAIN_PAGE = "User_Route_List.aspx?userID=";
    private const string EMPTY = "";

    private decimal mobileUserID = 0;
    private decimal routeID = 0;
    private OrgainzationManager orgManager = new OrgainzationManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[REQUEST_LIST_ID] != null)
        {
            decimal.TryParse(Request.QueryString[REQUEST_LIST_ID], out mobileUserID);
        }
        if (Request.QueryString[ROUTE_ID] != null)
        {
            decimal.TryParse(Request.QueryString[ROUTE_ID], out routeID);
        }
        if (txtHidOrg.Value == "")
        {
            if (mobileUserID > 0)
            {
                USERS user = new UserManager().GetUserByID(mobileUserID);
                if (user != null)
                {
                    txtHidOrg.Value = user.ORGID.ToString();
                    txtOrg.Text = new OrgainzationManager().Load(user.ORGID).NAME;
                    //
                    //显示其相应的所属部门和市场
                    DataTable dt = new ChainManager().GetChainTable(user.DOMAINID,user.ORGID.ToString(), "", "1");
                    string chainsList = "";
                    foreach (DataRow row in dt.Rows)
                        chainsList += (row["ID"] + "∞" + row["DESCRIPTION"] + "∮");
                    chainsList = chainsList.TrimEnd('∮');
                    txtHidChains.Value = chainsList;
                    //
                    dt = new RegionManager().GetRegionTable("", user.ORGID, (int)RegionLevel.county, "1", MyStateManager.DomainID);
                    string regionList = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        regionList += row["ID"] + "∞" + row["DISTRICT_NAME"] + "∮";
                    }
                    regionList = regionList.TrimEnd('∮');
                    txtHidCounty.Value = regionList;
                }
            }
        }
        //if (txtHidChains > EMPTY)
        //{            
        //    OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);            
        //}

        if (!IsPostBack)
        {
            txtOrg_TextChanged(sender, e);
            this.InitForm();
            BindChainsDDL();
            ddlAssigned.SelectedValue = "1";
            ddlAssigned.SelectedValue = "0";
        }
    }

    protected void SelectALL(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        if (chk == null)
            return;
        foreach (GridViewRow row in this.gvChannelType.Rows)
        {
            CheckBox checkbox = row.Cells[gvChannelType.Columns.Count - 1].FindControl("cbxSelected") as CheckBox;
            if (checkbox != null)
                checkbox.Checked = chk.Checked;
        }
    }

    /// <summary>
    /// Inits the form.
    /// </summary>
    private void InitForm()
    {
        if (mobileUserID > 0)
        {
            USERS mobileUser = new Jumpton.SFA.Server.BusinessRule.System.UserManager().GetUserByID(mobileUserID);
            if (mobileUser != null)
            {
                Jumpton.SFA.Server.Entity.Person person = new Jumpton.SFA.Server.BusinessRule.MasterData.PersonManager().Load((int)mobileUser.PERSONID);
                if (person != null)
                {
                    lblMobileUserInfo.Text = mobileUser.CODE + " " + person.Name;
                }                
            }
            else
            {
                lblMobileUserInfo.Text = "";
            }
        }

        //分配类型
        ddlAssigned.Items.Add(new ListItem("--所有--", "0"));
        ddlAssigned.Items.Add(new ListItem("已分配", "1"));
        ddlAssigned.Items.Add(new ListItem("未分配", "2"));


        DictionaryItemsManager dim = new DictionaryItemsManager();

        //销售渠道
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem("--所有--", EMPTY));
        
    }
    /// <summary>
    /// 经销商
    /// </summary>
    private void BindChainsDDL()
    {        
        ddlChains.Items.Clear();
        if (!string.IsNullOrEmpty(txtHidChains.Value))
        {
            string[] options = txtHidChains.Value.Split('∮');

            for (int i = 0; i < options.Length; i++)
            {
                string[] item = options[i].Split('∞');
                //
                ddlChains.Items.Add(new ListItem(item[1], item[0]));
            }
        }
        ddlChains.Items.Insert(0, new ListItem("--所有--", EMPTY));
    }

    /// <summary>
    /// Binds the grid.
    /// </summary>
    private DataTable BindGrid()
    {
        if (mobileUserID > 0)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            //HZJ注释于2010.5.6 原因：目前customers表中org_id很多为空，这个部门没有必要加上去。查找所有的门店就可以了.
            //if (!string.IsNullOrEmpty(txtHidOrg.Value))
            //{
                //sb.Append(string.Format(" AND C.ORG_ID IN ({0})", txtHidOrg.Value));
            //}

            if (txtCustomer.Text != EMPTY)
            {
                sb.Append(" AND (C.[CODE] LIKE '%" + txtCustomer.Text.Trim() + "%' or C.[NAME] LIKE '%" + txtCustomer.Text.Trim() + "%' AND C.DOMAIN_ID='" + this.MyStateManager.DomainID + "') ");
            }
            if (ddlChains.SelectedValue != EMPTY)
            {
                sb.Append(" And CHAINS.ID = '" + ddlChains.SelectedValue + "' ");
            }
            if (ddlChannel.SelectedValue != EMPTY)
            {
                sb.Append(" AND LOCAL_LEVEL1_CODE =  '" + ddlChannel.SelectedValue + "'  ");
            }



            DataSet ds = CustomerRouteManager.SearchCustomerForUser(mobileUserID, ddlAssigned.SelectedValue, MyStateManager.DomainID,int.Parse(txtHidOrg.Value), sb.ToString());
            if (ds != null && ds.Tables.Count > 0)
            {
               
                GridPager1.DataSource = ds.Tables[0];
                GridPager1.GridView = gvChannelType;
                GridPager1.BindData();
                GridPager1.Visible = gvChannelType.Rows.Count > 0;
            }
            return ds.Tables[0];
        }
        return null;
    }

    /// <summary>
    /// Handles the Click event of the btnQuery control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

   

    public void GridViewToolbarUserControl1_OnGVTBSetColumnsButtonEvent(object sender, EventArgs e)
    {
        BindGrid();
    }

    /// <summary>
    /// Handles the Click event of the btnCancel control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(RESPONSE_LIST_MAINTAIN_PAGE + mobileUserID.ToString());
    }


    protected void gvChannelType_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    /// <summary>
    /// 选择组织结构触发绑定行政架构(市场)事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        BindChainsDDL(); 

    }
   

    /// <summary>
    /// 全部提交
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmitAll_Click(object sender, EventArgs e)
    {
        decimal customerID = 0;
        decimal RCID = 0;
        CheckBox ckx = null;
        if( this.gvChannelType.HeaderRow!=null)
            ckx = this.gvChannelType.HeaderRow.FindControl("chkAll") as CheckBox;

        ROUTES route = new ROUTES();
        route.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));
        route.LAST_UPDATER = this.MyStateManager.Name;
        route.USERID = this.mobileUserID;
        route.ROUTENUMBER = 0;
        route.DESCRIPTION = "所有覆盖";

        CustomerRouteManager.CreateRoute(route);

        DataTable dt = BindGrid();

        if (mobileUserID > 0)
        {
            foreach (DataRow row in dt.Rows)
            {

                bool check = Convert.ToBoolean(row["Selected"].ToString());
                decimal.TryParse(row["id"].ToString(),out customerID);
                decimal.TryParse(row["RCID"].ToString(), out RCID);

                if (ckx != null && customerID > 0)
                {
                    ROUTE_CUSTOMERS routeManager = new ROUTE_CUSTOMERS();
                    routeManager.ID = RCID;
                    routeManager.USERID = mobileUserID;
                    routeManager.ROUTENUMBER = 0;
                    routeManager.CUSTOMERID = customerID;
                    routeManager.SEQUENCE = 0;
                    routeManager.LAST_UPDATER = MyStateManager.UserID.ToString();
                    routeManager.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));

                    UserManager userManager = new UserManager();
                    USERS user = userManager.GetUserByID(routeManager.USERID);

                    CustomerManager cstManager = new CustomerManager();
                    CUSTOMERS customer = cstManager.Load(routeManager.CUSTOMERID);

                    if (ckx.Checked && RCID == 0 && user.ORGID != customer.ORGID)
                    {
                        continue;
                    }
                    else
                    {
                        CustomerRouteManager.AssignCustomerForUser(ckx.Checked, RCID != 0, RCID, routeManager, MyStateManager.DomainID);
                    }
                }
            }
        }

        Response.Redirect(RESPONSE_LIST_MAINTAIN_PAGE + mobileUserID.ToString());


    }


    /// <summary>
    /// Handles the Click event of the btnSubmit control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        
        System.Text.StringBuilder falidCustomers = new System.Text.StringBuilder();

        decimal customerID = 0;
     

        ROUTES route = new ROUTES();
        route.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));
        route.LAST_UPDATER = this.MyStateManager.Name;
        route.USERID = this.mobileUserID;
        route.ROUTENUMBER = 0;
        route.DESCRIPTION = "所有覆盖";
        route = CustomerRouteManager.CreateRoute(route);
      
        if (mobileUserID > 0)
        {
            UserManager userManager = new UserManager();
            USERS user = userManager.GetUserByID(mobileUserID);
            for (int i = 0; i < gvChannelType.Rows.Count; i++)
            {
                CheckBox ckx = new CheckBox();
                Control ctl = gvChannelType.Rows[i].FindControl("cbxSelected");
                if (ctl != null)
                {
                    ckx = ctl as CheckBox;
                }
                decimal RCID = 0;
                decimal.TryParse(gvChannelType.DataKeys[i].Values[0].ToString(), out customerID);
                decimal.TryParse(gvChannelType.DataKeys[i].Values[1].ToString(), out RCID);


                if (ckx != null && customerID > 0)
                {
                    ROUTE_CUSTOMERS routeManager = new ROUTE_CUSTOMERS();
                    routeManager.ID = RCID;
                    routeManager.USERID = mobileUserID;
                    routeManager.ROUTENUMBER = 0;
                    routeManager.CUSTOMERID = customerID;
                    routeManager.SEQUENCE = 0;
                    routeManager.LAST_UPDATER = MyStateManager.UserID.ToString();
                    routeManager.LAST_UPDATE_TIME = Decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));

                 
                   

                    CustomerManager cstManager = new CustomerManager();
                    CUSTOMERS customer = cstManager.Load(routeManager.CUSTOMERID);

                    if (ckx.Checked && RCID == 0 && user.ORGID != customer.ORGID)
                    {
                        falidCustomers.AppendFormat("{0},", customer.NAME);
                    }
                    else
                    {
                        CustomerRouteManager.AssignCustomerForUser(ckx.Checked, RCID != 0, RCID, routeManager, MyStateManager.DomainID);
                    }
                }
            }
        }

        //判断是否有，不是同一组织的门店
        if (!string.IsNullOrEmpty(falidCustomers.ToString().TrimEnd(',')))
        {
            ShowMessage(string.Format("由于客户与业代不属于同一组织，导致无法新增线路。失败客户:{0}",
                                        falidCustomers.ToString().TrimEnd(',')));
            BindGrid();
        }
        else
        {
            Response.Redirect(RESPONSE_LIST_MAINTAIN_PAGE + mobileUserID.ToString());
        }

    }

   
}